package com.example.graduationdesignbackend.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.graduationdesignbackend.constants.ResponseCode;
import com.example.graduationdesignbackend.dto.PageDto;
import com.example.graduationdesignbackend.dto.UserLoginDto;
import com.example.graduationdesignbackend.dto.UserVo;
import com.example.graduationdesignbackend.entity.User;
import com.example.graduationdesignbackend.exception.ParkException;
import com.example.graduationdesignbackend.mapper.UserMapper;
import com.example.graduationdesignbackend.query.UserQuery;
import com.example.graduationdesignbackend.res.Res;
import com.example.graduationdesignbackend.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yuze
 * @since 2024-04-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public SaTokenInfo login(UserLoginDto request) {
        String userCode = request.getCode();
        String phone = request.getPhone();
        Object redis_code = redisTemplate.opsForValue().get("check:code:" + phone);
        if(redis_code == null ) throw new ParkException(ResponseCode.Fail, "验证码错误");
        if ( !redis_code.equals(userCode)) throw new ParkException(ResponseCode.Fail, "验证码错误");
        //1.查询用户是否存在
        User user = lambdaQuery().eq(User::getPhone, request.getPhone()).one();
        //2.不存在 自动创建用户
        if (BeanUtil.isEmpty(user)) {
            user = new User();
            user.setId(RandomUtil.randomNumbers(9));
            user.setPhone(String.valueOf(request.getPhone()));
            user.setCreateTime(new Date().getTime());
            user.setPower("admin");
            user.setStatus(9);
            boolean save = save(user);
            if (!save) throw new ParkException(ResponseCode.Fail);
        }else{
            user.setUpdateTime(new Date().getTime());
            boolean update = updateById(user);
            if (!update) throw new ParkException(ResponseCode.Fail);
        }
        User user1 = lambdaQuery().eq(User::getPhone, request.getPhone()).one();
        StpUtil.login(user1.getId());
        return StpUtil.getTokenInfo();
    }

    @Override
    public SaTokenInfo loginpwd(UserLoginDto request) {
        User user = lambdaQuery().eq(User::getPhone,request.getPhone()).one();
        if (BeanUtil.isEmpty(user)) throw new ParkException(ResponseCode.NotFindError);
        if (!user.getPassword().equals(request.getPassword()))throw new ParkException(ResponseCode.Fail,"手机号或密码错误！");
        user.setUpdateTime(new Date().getTime());
        Boolean update = updateById(user);
        if (!update) throw  new ParkException(ResponseCode.Fail);
        StpUtil.login(user.getId());
        return StpUtil.getTokenInfo();
    }


    @Override
    public void getLoginCode(String phone) {
        redisTemplate.opsForValue().set("check:code:" + phone, "123456", 120, TimeUnit.SECONDS);
    }

    @Override
    public Res editPassword(User user1) {
        String id = StpUtil.getLoginIdAsString();
        User user = lambdaQuery().eq(User::getId,id).one();
        user.setPassword(user1.getPassword());
        Boolean update = updateById(user);
        if (!update) throw new ParkException(ResponseCode.Fail);
        return Res.yuze();
    }

    @Override
    public User getInfo(String id) {
        return getById(id);
    }
    
    @Override
    public Res editInfo(User user) {
        User user1 = getById(user.getId());
        if (!BeanUtil.isEmpty(user.getImage())){
            user1.setImage(user.getImage());
        }
        if (!BeanUtil.isEmpty(user.getNickName())){
            user1.setNickName(user.getNickName());
        }
        user1.setUpdateTime(new Date().getTime());
        Boolean update = updateById(user);
        if (!update) throw new ParkException(ResponseCode.Fail);
        return Res.yuze();
    }
    
    @Override
    public Res getPage(UserQuery dto) {
        String key = dto.getKey();
        int current = 1;
        if (!BeanUtil.isEmpty(dto.getCurrent())){
            current = dto.getCurrent();
        }
        int pageSize = 10;
        if (!BeanUtil.isEmpty(dto.getPageSize())){
            pageSize = dto.getPageSize();
        }
        Page<User> page = Page.of(current,pageSize);
        page.addOrder(new OrderItem("create_time",false));
        Page<User> p = new Page<>();
        if (BeanUtil.isEmpty(dto.getKey())){
            p = lambdaQuery()
                    .page(page);
        }else {
            p = lambdaQuery()
                    .like(User::getPhone,key)
                    .page(page);
        }
        List<UserVo> list = new ArrayList<>();
        for (int i=0;i<p.getRecords().size();i++){
            list.add(BeanUtil.toBean(p.getRecords().get(i),UserVo.class));
        }
        PageDto<UserVo> dto1 = new PageDto<>();
        dto1.setTotal(p.getTotal());
        dto1.setPages(p.getPages());
        dto1.setPageSize(p.getSize());
        dto1.setCurrent(p.getCurrent());
        dto1.setList(list);
        return Res.yuze(dto1);
    }

}
